package edu.sju.ssm.config;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@PropertySource({"classpath:jdbc.properties"})
@EnableTransactionManagement
public class DataAccessConfig {
	// Inject jdbc property values into the fields.
	// Alternatively, they can also be placed as arguments of DataSource methods
	@Value("${jdbc.driverClassName}") String driverClassName;
	@Value("${jdbc.url}") String url;
	@Value("${jdbc.username}") String username;
	@Value("${jdbc.password}") String password;

	@Bean
	public TransactionManager transactionManager(@Value("#{dataSource}") DataSource dataSource) {
		DataSourceTransactionManager result = new DataSourceTransactionManager(dataSource);
		return result;
	}
	
	@Bean
	public JdbcTemplate jdbcTemplate(@Value("#{dataSource}") DataSource dataSource) {
		JdbcTemplate result = new JdbcTemplate(dataSource);
		return result;
	}
	
	@Bean(destroyMethod = "close")
	public DataSource dataSource() {
		BasicDataSource result = new BasicDataSource();
		result.setDriverClassName(driverClassName);
		result.setUrl(url);
		result.setUsername(username);
		result.setPassword(password);
		return result;
	}
	
	@Bean
	public DataSource springDataSource() {
		DriverManagerDataSource result = new DriverManagerDataSource();
		result.setDriverClassName("com.mysql.cj.jdbc.Driver");
		result.setUrl("jdbc:mysql://localhost:3306/bookdb");
		result.setUsername("root");
		result.setPassword("123456");
		return result;
	}
	
}
